/**
 * Created by lijizhuang on 16/9/19.
 */
define(['jquery', 'underscore', 'backbone', 'common', 'url', 'text!modules/roomTypesMgr/modal/newRoomTypeView.html', 'utils/regutil', 'models/roomTypesMgr/roomType',
    'models/roomTypesMgr/roomModel', 'models/roomTypesMgr/roomModels', 'models/roomTypesMgr/defaultPrice', 'common', 'extensions/stringExts', 'bootstrap-dialog'],
    function ($, _, Backbone, Common, Url, NewRoomTypeViewTemplate, RegUtil, RoomType, RoomModel, RoomModels, DefaultPrice, Common, StringExts, BootstrapDialog) {
        var newRoomTypeView = Backbone.View.extend({
            tagName: 'div',
            id: 'newRoomType',
            className: 'modal fade',
            template: _.template(NewRoomTypeViewTemplate),

            initialize: function (attrs) {
                _newRoomTypeView = this;
                this.options = attrs;
            },

            events: {
                'click .addRoom': 'onAddRoomClick',
                'click .removeRoom': 'onRemoveRoomClick',
                'keyup input#initPrice': 'onDefaultPriceEnter',
                'change .weekday-price-item input': 'onWeekdayPriceEnter',
                'click .new-roomtype-footer #saveBtn': 'onSaveClick',
                'focusin input': 'onTextboxFocus'
            },

            onAddRoomClick: function (e) {
                var ele = "<div class=\"roomUnit\"><div style='position: relative'><input type=\"text\" data-roomid=0 class=\"roomInput\" name=\"roomInputTB\"></div><div class='removeRoom'></div></div>";
                $(ele).insertBefore($(e.currentTarget));
                //添加房间,滚动条默认滚到最后
                $(".new-roomtype-body").scrollTop($(".new-roomtype-body").get(0).scrollHeight);
            },

            onRemoveRoomClick: function (e) {
                $(e.currentTarget).parent().remove();
            },

            onDefaultPriceEnter: function (e) {
                var price = $(e.currentTarget).val();
                $('.new-roomtype-body input#mondayPrice').val(price);
                $('.new-roomtype-body input#tuesdayPrice').val(price);
                $('.new-roomtype-body input#wednesdayPrice').val(price);
                $('.new-roomtype-body input#thursdayPrice').val(price);
                $('.new-roomtype-body input#fridayPrice').val(price);
                $('.new-roomtype-body input#saturdayPrice').val(price);
                $('.new-roomtype-body input#sundayPrice').val(price);

                if (!RegUtil.numberReg.test(price)) {
                    _newRoomTypeView.showError($(e.currentTarget), '输入数字');
                }
                else {
                    _newRoomTypeView.clearError($(e.currentTarget));
                }

                //手动通知及联修改检测http://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery
                $(".new-roomtype-body .weekday-price-item input[type=text]").trigger("change");
            },

            onWeekdayPriceEnter: function (e) {
                var price = $(e.currentTarget).val();

                if (!RegUtil.numberReg.test(price)) {
                    _newRoomTypeView.showError($(e.currentTarget), '输入数字');
                }
                else if (price < 1 || price > 9999)
                {
                    _newRoomTypeView.showError($(e.currentTarget), '1 -> 9999');
                }
                else {
                    _newRoomTypeView.clearError($(e.currentTarget));
                }
            },

            onSaveClick: function () {
                var valid_success = true;

                var $roomTypeName = $('.new-roomtype-body .roomtype-name-item #roomTypeName');
                if ($roomTypeName.val().trim().length === 0) {
                    _newRoomTypeView.showError($roomTypeName, '不能为空', 'bottom');
                    valid_success = false;
                }
                else if ($.trim($roomTypeName.val()).gbLength() > 20) {
                    _newRoomTypeView.showError($roomTypeName, '限20个字符', 'bottom');
                    valid_success = false;
                }
                else {
                    _newRoomTypeView.clearError($roomTypeName);
                }

                var $notes = $('.new-roomtype-body input#notes');
                if ($.trim($notes.val()).gbLength() > 50) {
                    _newRoomTypeView.showError($notes, '限50个字符', 'bottom');
                    valid_success = false;
                }

                var $initPrice = $('.new-roomtype-body input#initPrice');
                if (!RegUtil.numberReg.test($initPrice.val())) {
                    _newRoomTypeView.showError($initPrice, '输入数字', 'top');
                    valid_success = false;
                }
                else if ($initPrice.val() < 1 || $initPrice.val() > 9999) {
                    _newRoomTypeView.showError($initPrice, '1 -> 9999');
                    valid_success = false;
                }
                else {
                    _newRoomTypeView.clearError($initPrice);
                }

                $('.new-roomtype-body .weekday-price-item input').each(function () {
                    if (!RegUtil.numberReg.test($(this).val())) {
                        _newRoomTypeView.showError($(this), '输入数字');
                        valid_success = false;
                    }
                    else if ($(this).val() < 1 || $(this).val() > 9999) {
                        _newRoomTypeView.showError($(this), '1 -> 9999');
                        valid_success = false;
                    }
                    else {
                        _newRoomTypeView.clearError($(this));
                    }
                });

                $('.new-roomtype-body input.roomInput').each(function () {
                    if ($(this).val().trim().length === 0) {
                        _newRoomTypeView.showError($(this), '输入房号', 'top');
                        valid_success = false;
                    }
                    else if ($.trim($(this).val()).gbLength() > 10) {
                        _newRoomTypeView.showError($(this), '限10个字符', 'top');
                        valid_success = false;
                    }
                    else {
                        _newRoomTypeView.clearError($(this));
                    }
                });

                //验证通过
                if (valid_success) {

                    //构建新建房型数据
                    var postModel = {};
                    postModel.roomTypeName = $('.new-roomtype-body input#roomTypeName').val();
                    postModel.bnbId = this.options.bnbId;
                    postModel.notes = $('.new-roomtype-body input#notes').val();

                    var rooms = [];
                    $('.new-roomtype-body input.roomInput').each(function () {
                        var room = {};
                        room.roomNumber = $(this).val();
                        room.bnbId = postModel.bnbId;
                        room.enabled = true;
                        rooms.push(room);
                    });

                    var commonPrice = {};
                    commonPrice.initPrice =  parseFloat($('.new-roomtype-body input#initPrice').val()).toFixed(2);
                    commonPrice.mondayPrice = parseFloat($('.new-roomtype-body input#mondayPrice').val()).toFixed(2);
                    commonPrice.tuesdayPrice = parseFloat($('.new-roomtype-body input#tuesdayPrice').val()).toFixed(2);
                    commonPrice.wednesdayPrice = parseFloat($('.new-roomtype-body input#wednesdayPrice').val()).toFixed(2);
                    commonPrice.thursdayPrice = parseFloat($('.new-roomtype-body input#thursdayPrice').val()).toFixed(2);
                    commonPrice.fridayPrice = parseFloat($('.new-roomtype-body input#fridayPrice').val()).toFixed(2);
                    commonPrice.saturdayPrice = parseFloat($('.new-roomtype-body input#saturdayPrice').val()).toFixed(2);
                    commonPrice.sundayPrice = parseFloat($('.new-roomtype-body input#sundayPrice').val()).toFixed(2);

                    postModel.newRoomList = rooms;
                    postModel.commonPrice = commonPrice;

                    //提交模型到服务端
                    Common.sendAjaxRequest(Url.newRoomType, postModel, _.bind(function (data) {
                        if (data.Content && data.Content.length > 0)
                        {
                            var createdRoomType = JSON.parse(data.Content);

                            var rtObj = createdRoomType.roomType;
                            var roomType = new RoomType();

                            var roomModels = new RoomModels();
                            for (var r in createdRoomType.rooms) {
                                var rObj = createdRoomType.rooms[r];
                                var roomModel = new RoomModel();
                                roomModel.set({
                                    rank: rObj.rank,
                                    roomId: rObj.roomId,
                                    roomNumber: rObj.roomNumber,
                                    roomTypeId: rtObj.roomTypeId,
                                    enabled: rObj.enabled,
                                    bnbId: rtObj.bnbId,
                                    roomTypeName: rtObj.roomTypeName
                                });
                                roomModels.add(roomModel);
                            }

                            var defaultPrice = new DefaultPrice();
                            var commonPriceObj = createdRoomType.commonPrice;
                            defaultPrice.set({
                                roomTypeId: rtObj.roomTypeId,
                                initPrice: commonPriceObj.initPrice,
                                mondayPrice: commonPriceObj.mondayPrice,      //周一至周末每天的价格
                                tuesdayPrice: commonPriceObj.tuesdayPrice,
                                wednesdayPrice: commonPriceObj.wednesdayPrice,
                                thursdayPrice: commonPriceObj.thursdayPrice,
                                fridayPrice: commonPriceObj.fridayPrice,
                                saturdayPrice: commonPriceObj.saturdayPrice,
                                sundayPrice: commonPriceObj.sundayPrice
                            });

                            var sort = this.collection.length + 1;
                            roomType.set({
                                roomTypeId: rtObj.roomTypeId,  //房型id
                                roomTypeName: rtObj.roomTypeName, //房型名
                                roomTypeNotes: rtObj.notes, //房型备注
                                bnbId: rtObj.bnbId,  //民宿id
                                rank: rtObj.rank,  //房型排名
                                sort: sort, //房型在当前Bnb的排序 
                                roomModels: roomModels,  //房间集合
                                defaultPrice: defaultPrice //价格信息
                            });

                            this.collection.add(roomType);
                            this.$el.modal('hide');
                        }
                    }, this), _.bind(function (data) {
                        if (data.Content && data.Content.length > 0) {
                            BootstrapDialog.show({
                                title: '系统提示',
                                message: data.Content
                            });
                        }
                    }, this), false);

                }

            },

            onTextboxFocus: function (e) {
                $(e.currentTarget).tooltip('hide');
                _newRoomTypeView.clearError($(e.currentTarget));
            },

            showError: function (target, wording, place) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('*'+wording);
                if (!target.hasClass('validate-failed')) {
                    target.addClass('validate-failed');
                }

                place = (place === undefined || place.length === 0) ? 'top' : place; //默认为top

                target.tooltip({ 'trigger': 'manual', 'title': wording, 'placement': place });
                target.attr('data-original-title', wording).tooltip('show'); //不能直接target.tooltip('show'),文本替换无效
            },

            clearError: function (target) {
                //var $errMsg = $('#newRoomType .errorMsg');
                //$errMsg.html('');

                if (target.hasClass('validate-failed')) {
                    target.removeClass('validate-failed');
                }

                target.tooltip('hide');
            },


            render: function () {
                this.$el.html(this.template());

                return this;
            }
        });

        return newRoomTypeView;
    });